using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DocLibApp
{
    public partial class FormBase : Form
    {
        #region Shared variables
        //definition
        //default config filename
        //protected string DatabaseFileName = @"doclibmain.mdb";
        protected string SQLiteDatabaseFileName = @"doclib.dat";
        protected string DocumentPath = @"c:\doc";
        protected int iFailAttemptNo = 3;

        protected string MainFormTitle = "";

        //shared variables
        protected System.Collections.Hashtable settingHash = new System.Collections.Hashtable();
        #endregion

        public FormBase()
        {
            InitializeComponent();

            mytoolTip.ToolTipTitle = Application.ProductName + " v" + Application.ProductVersion;
        }

        #region protected functions
        /// <summary>
        /// open new midi first check if there's a child window instance already running,
        /// if running, active instead of openning up a new midi child window
        /// </summary>
        /// <param name="aForm"></param>
        protected void OpenNewMdi(Form aForm)
        {
            //want to compare form text even though maybe the same form type, such as Document form
            foreach (System.Windows.Forms.Form aChild in this.MdiChildren)
            {
                if (aChild.GetType().FullName == aForm.GetType().FullName)
                {
                    aChild.BringToFront();
                    return;
                }
            }

            aForm.MdiParent = FormMain.DocLibFormMain;

            //aForm.MdiParent = this; //this sets the new form to be a mdi child form
            //aForm.Dock = DockStyle.Fill;
            aForm.Show();
        }

        protected void HandleEx(System.Exception ex)
        {
            eh myeh = new eh(true);
            myeh.WriteExpLog(ex);
            myeh.ShowExp(ex);
        }

        protected void sleep(int seconds)
        {
            System.Threading.Thread.Sleep(seconds * 1000);
        }

        protected void wait_start()
        {
            this.Text = Application.ProductName + " v" + Application.ProductVersion;
            this.Cursor = Cursors.WaitCursor;
        }

        protected void wait_start(string msg)
        {
            //this.Text = Application.ProductName + " v" + Application.ProductVersion + " - (" + msg + ")";
            this.Cursor = Cursors.WaitCursor;
        }

        protected void wait_end()
        {
            //this.Text = MainFormTitle;
            
            this.Cursor = Cursors.Default;
        }

        protected void ClearValuesFromControls(Control.ControlCollection ctls)
        {
            foreach (Control ctl in ctls)
            {
                if (ctl is TextBox)
                {
                    (ctl as TextBox).Text = "";
                }
                else if (ctl is ComboBox)
                {
                    (ctl as ComboBox).SelectedIndex = 0;
                }
                else if (ctl is DateTimePicker)
                {
                    (ctl as DateTimePicker).Value = System.DateTime.Now;
                }
            }
        }

        /// <summary>
        /// load the value of controls into key = value pair in hash table. Based on the control's tag
        /// only handles combo box & text box
        /// </summary>
        /// <param name="ctls"></param>
        /// <returns></returns>
        protected System.Collections.Hashtable SaveDataToHashFromControls(Control.ControlCollection ctls)
        {
            System.Collections.Hashtable ht = new System.Collections.Hashtable();

            foreach (Control ctl in ctls)
            {
                string key = "";
                if (ctl.Tag != null)
                    key = ctl.Tag.ToString();

                if (ctl is System.Windows.Forms.ComboBox)
                {
                    string value = "";

                    ComboBox cbo = ctl as ComboBox;
                    if (cbo.SelectedValue != null)
                        value = cbo.SelectedValue.ToString().Trim();
                    else
                        value = cbo.Text.Trim();

                    if (value != "0")
                        ht[key] = value;
                }
                else if (ctl is System.Windows.Forms.TextBox)
                {
                    string value = (ctl as TextBox).Text.Trim();
                    if (!String.IsNullOrEmpty(value))
                    {
                        if (key == "PASSWORD")
                            ht[key] = util.MaskString(value);
                        else
                            ht[key] = value;
                    }
                }
                else if (ctl is DateTimePicker)
                {
                    DateTimePicker aDateTimePicker = (ctl as DateTimePicker);
                    
                    if (aDateTimePicker.Checked)
                    {
                        if (aDateTimePicker.Value != null)
                        {
                            string value = SQLiteDB.DateTimeToString(aDateTimePicker.Value);
                            ht[key] = value;
                        }
                    }                                        
                }
                else if (ctl is UC_Keyword)
                {
                    string value = (ctl as UC_Keyword).GetKeywordList();
                    ht[key] = value;
                }
            }

            return ht;
        }

        /// <summary>
        /// Load hash table values into Controls (only combo box & text box)
        /// </summary>
        /// <param name="ctls"></param>
        /// <param name="ht"></param>
        protected void LoadDataFromHashToControls(Control.ControlCollection ctls, System.Collections.Hashtable ht)
        {
            foreach (Control ctl in ctls)
            {
                if (ctl.Tag != null && !string.IsNullOrEmpty(ctl.Tag.ToString()))
                {
                    string tagname = ctl.Tag.ToString().Trim();

                    if (ht[tagname] != null && !string.IsNullOrEmpty(ht[tagname].ToString()))
                    {
                        string value = ht[tagname].ToString().Trim();

                        if (value != "<NULL>")
                        {
                            if (ctl is ComboBox)
                            {
                                ComboBox cbx = ctl as ComboBox;
                                cbx.SelectedValue = value;
                            }
                            else if (ctl is TextBox)
                            {
                                TextBox tbx = ctl as TextBox;

                                if (tagname == "PASSWORD")
                                    tbx.Text = util.UnmaskString(value);
                                else
                                    tbx.Text = value;
                            }
                            else if (ctl is DateTimePicker)
                            {
                                DateTimePicker dtp = ctl as DateTimePicker;
                                dtp.Value = SQLiteDB.StringToDateTime(value);
                                dtp.Checked = true;
                            }
                            else if (ctl is UC_Keyword)
                            {
                                UC_Keyword mykeyword = ctl as UC_Keyword;
                                mykeyword.LoadKeywordList(value);
                            }
                        }
                    }
                }
            }
        }

        protected void ShowMessage(string msg)
        {
            if (!string.IsNullOrEmpty(msg))
                MessageBox.Show(msg, Application.ProductName + " v" + Application.ProductVersion, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// Select a file to save or open
        /// </summary>
        /// <param name="mode">0: save file; 1: open file</param>
        /// <param name="title"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        protected string SelectFile(int mode, string title, string filter, string defaultFileName)
        {
            switch (mode)
            {
                case 0:
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Title = title;
                    sfd.Filter = filter;
                    sfd.FilterIndex = 1;

                    if (defaultFileName.Trim() != "")
                        sfd.FileName = defaultFileName;

                    if (sfd.ShowDialog() == DialogResult.OK)
                        return sfd.FileName;
                    break;
                case 1:
                    OpenFileDialog ofd = new OpenFileDialog();
                    ofd.Title = title;
                    ofd.Filter = filter;
                    ofd.FilterIndex = 1;
                    ofd.Multiselect = false;
                    if (ofd.ShowDialog() == DialogResult.OK)
                        return ofd.FileName;
                    break;
            }

            return "";
        }

        protected bool ConfirmToProcess(string Question)
        {
            if (MessageBox.Show(Question, "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                return true;
            else
                return false;
        }

        protected string AddItemToList(string list, string item)
        {
            if (list.Trim() != "")
                list += "," + item;
            else
                list = item;

            return list;
        }

        protected string GetSetting(string key)
        {
            if (settingHash != null && settingHash[key] != null)
                return settingHash[key].ToString().Trim();

            return "";
        }

        /// <summary>
        /// get description for application code defined in table
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected string GetAppCode(string key)
        {
            return doc_system.GetCodeDescription(def.CG_App_Code, key);
        }

        protected void SetAppCode(string key, string value)
        {
            doc_system.SetCodeDescription(def.CG_App_Code, key, value);
        }

        protected string GetSettingString(string key, string variablevalue)
        {
            if (settingHash != null & settingHash[key] != null && settingHash[key].ToString().Trim() != "")
            {
                return settingHash[key].ToString().Trim();
            }

            return variablevalue;
        }

        protected bool GetSettingBoolean(string key)
        {
            if (settingHash != null && settingHash[key] != null && settingHash[key].ToString().Trim().ToUpper() == "TRUE")
                return true;

            return false;
        }

        protected int GetSettingInt(string key, int defaultValue)
        {
            int res = defaultValue;

            try
            {
                if (settingHash != null && settingHash[key] != null && settingHash[key].ToString().Trim() != "")
                {
                    res = Int32.Parse(settingHash[key].ToString().Trim());
                }
            }
            catch (System.Exception ex)
            {
                HandleEx(ex);
                res = defaultValue;
            }

            return res;
        }

        protected void SaveSetting(string key, string val)
        {
            if (settingHash != null)
            {
                settingHash[key] = val;
            }
        }

        protected void SendEmail(string subject, string message)
        {
            string email_smtp = GetSetting("email_SMTP");
            string email_to = GetSetting("email_TO");
            string email_from = GetSetting("email_FROM");

            util.SendEmail(email_smtp, email_from, email_to, subject, message);
        }

        protected string PickTemplate()
        {
            System.Collections.ArrayList TemplateList = doc_template.GetListOfTemplates();

            FormDatabaseSelect fds = new FormDatabaseSelect();
            fds.Title = "Please select a template";
            fds.OpenSelection(TemplateList, "TEMPLATE_ID");

            fds.ShowDialog();
            return fds.SelectedID;
        }

        protected string PickRole()
        {
            System.Collections.ArrayList RoleList = doc_security.GetListOfRoles();

            FormDatabaseSelect fds = new FormDatabaseSelect();
            fds.Title = "Please select a security role";
            fds.OpenSelection(RoleList, "ROLE_ID");

            fds.ShowDialog();
            return fds.SelectedID;
        }

        protected string PickUser()
        {
            System.Collections.ArrayList UserList = doc_security.Get_List_Users();

            FormDatabaseSelect fds = new FormDatabaseSelect();
            fds.Title = "Please select a user to edit";
            fds.OpenSelection(UserList, "USERNAME");

            fds.ShowDialog();
            return fds.SelectedID;
        }

        /// <summary>
        /// select from a list of documents to open
        /// </summary>
        protected void SelectDocumentToOpen()
        {
            wait_start();

            List<string> FieldList = new List<string>();
            FieldList.Add("DOC_ID");
            FieldList.Add("TITLE");
            FieldList.Add("CATEGORY");
            FieldList.Add("TYPE");
            FieldList.Add("NOTE");
            FieldList.Add("DT_DOC");

            System.Collections.Hashtable ht = new System.Collections.Hashtable();

            FormMain.DocLib_QB.TableName = def.tb_doc;
            FormMain.DocLib_QB.Get_Select(FieldList, ht);
            System.Collections.ArrayList alist = FormMain.DocLib_QB.GetDataRow_ArrayList(true);

            wait_end();

            FormDatabaseSelect fds = new FormDatabaseSelect();
            fds.Title = "Please select a document to open";
            fds.OpenSelection(alist, "DOC_ID", def.tb_doc);
            fds.ShowDialog();
            string doc_id = fds.SelectedID;

            if (!string.IsNullOrEmpty(doc_id))
                OpenDocument(doc_id);
        }

        protected void OpenDocument(string doc_id)
        {
            FormDocument fdoc = new FormDocument();
            if (fdoc.OpenDocument(doc_id))
                OpenNewMdi(fdoc);
        }
        #endregion
    }
}